//
//  LoginVC.m
//  DataStatistics
//
//  Created by Kang on 15/12/24.
//  Copyright © 2015年 YTYangK. All rights reserved.
//

#import "LoginVC.h"
#import "LoginViewModel.h"
#import "UITextField+LolitaText.h"

@interface LoginVC ()<UITextFieldDelegate,UITextViewDelegate>
{
    /** 初始化位置*/
    CGRect frameDefault;
    /** 判断是否点击了 */
    BOOL   isClick;
}

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *W_keepPassword;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *H_login;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *W_login;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_login;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_pas;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_ame;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_acount;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *Y_forget;

@end

@implementation LoginVC

//singleton_for_implementation(LoginVC)

- (void)viewDidLoad {
    [super viewDidLoad];
   self.password.delegate              = self;
    self.phoneNum.delegate              = self;
    [self setTextFunction];
    [self setChoiceBoxFunction];
    
    if (SCREEN_WIDTH == 414) {
    }else if(SCREEN_WIDTH == 375){
    }else {
        if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
            self.Y_pas.constant +=  5;
            self.Y_ame.constant -=  5;
            self.Y_login.constant +=  27;
            self.Y_forget.constant = self.Y_acount.constant  +=  5;
        }
        self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:23];
        self.W_login.constant =  self.H_login.constant = 86;  //self.H_login.constant  -=  26;
        
    }
    
    UITapGestureRecognizer *tapGetstureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGetstureRecognizer.cancelsTouchesInView = YES;        //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    [self.view addGestureRecognizer:tapGetstureRecognizer]; //将触摸事件添加到当前view
    
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    
}
/*- (void)updateViewConstraints {
     [super updateViewConstraints];
}*/



/** text设置 */
- (void)setTextFunction{
    frameDefault = self.view.frame;
    _signStr = @"";
 
    if (SCREEN_WIDTH == 320) {
        self.reclsTeredBtn.titleLabel.font = self.forcetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        self.phoneNum.font  = self.password.font = [UIFont systemFontOfSize:20];
    }
    
    [self.phoneNum addYTYanKTextFielStyle1:self.phoneNum withString:NSLocalizedString(@"LVCAcc",nil)];
    [self.phoneNum addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    
     self.password.secureTextEntry       =  YES; //密码类型
    self.password.clearsOnBeginEditing = NO;
     self.password.returnKeyType         = UIReturnKeyGo;
    [self.password addYTYanKTextFielStyle1:self.password withString:NSLocalizedString(@"LVCPas",nil)];
    [self.password addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];

    [self rememberAction];
}

- (void)LVCtextLengthMethod:(UITextField *)textField {
    BOOL established = (self.password.text.length > 0) && (self.phoneNum.text.length > 0);
   // BOOL established2 = ([self.password.text isEqualToString:@""] && [self.password.text isEqualToString:@""]);
    
    
    if (established) {
        self.password.enablesReturnKeyAutomatically  = NO;
        self.loginBtn.userInteractionEnabled   = YES;
    }else {
        self.password.enablesReturnKeyAutomatically  = YES;
        self.loginBtn.userInteractionEnabled = NO;
    }
    
    if(textField.tag == 1 ){
        if (textField == self.phoneNum) {
            if (textField.text.length > 15) {
                textField.text = [textField.text substringToIndex:15];
            }
        }
    }
    else {
        if (textField == self.password) {
            if (textField.text.length > 15) {
                textField.text = [textField.text substringToIndex:12];
            }
        }
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _phoneNum) {
        [_password becomeFirstResponder];
    }else {
         [self resignRespondersForTextFields];
         [self loginBtnCiake:_loginBtn];
    }
    return  YES;
}


// 判断登录前操作是否合法
- (NSString *)checkUserDetails {
    NSCharacterSet *whiteNewChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *userName = [self.phoneNum.text stringByTrimmingCharactersInSet:whiteNewChars];
    NSString *password = [self.password.text stringByTrimmingCharactersInSet:whiteNewChars];
    NSString *message = @"";
    
    if ([userName length] == 0 || [password length] == 0) {
        message = [NSString stringWithFormat:NSLocalizedString(@"LVCP1", nil)];
    }else {
        if ([self.phoneNum.text rangeOfString:@" "].location != NSNotFound) {
            message = [NSString stringWithFormat:NSLocalizedString(@"LVCP2",nil)];
        }else {
            if ([password length] < 2) {
                message  = [NSString stringWithFormat:NSLocalizedString(@"LVCP3",nil)];
            }
        }
    }
    return message;
}

- (BOOL)resignRespondersForTextFields {
    if (isClick) {
        isClick = NO;
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0") ){
            [UIView animateWithDuration:0.24 animations:^{
                [self.view setFrame:frameDefault];
            } completion:nil];
        }
        
        [_phoneNum resignFirstResponder];
        [_password resignFirstResponder];
    }
    return isClick;
}


/** 键盘显示  */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (!isClick) {
        isClick = YES;
    }
    if (_phoneNum.isFirstResponder == true || _password.isFirstResponder == true) {
         CGRect newFrome = self.view.frame;
        if (SCREEN_HEIGHT == 480 ) {
            newFrome.origin.y = -2 * textField.frame.size.height - 40;
        } else if (SCREEN_HEIGHT == 568) {
            newFrome.origin.y =   -1 * textField.frame.size.height - 20;
        }
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        } completion:^(BOOL finished) {
            
        }];
    }
}
/** 键盘隐藏 */
- (void)keyboardHide:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
         [self resignRespondersForTextFields];
    }
}


/** 按钮设置 */
- (void)setChoiceBoxFunction {
    [self.loginBtn setTitle:NSLocalizedString(@"LVCLogIn", nil) forState:UIControlStateNormal];
    [self.reclsTeredBtn setTitle:NSLocalizedString(@"LVCSignUp", nil) forState:UIControlStateNormal];
    [self.forcetPasswordBtn setTitle:NSLocalizedString(@"LVCForgot", nil) forState:UIControlStateNormal];
    [self.reclsTeredBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
    [self.forcetPasswordBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
}
/** singUp Or Forgot 按钮跳转设置 */
- (void)ChoiceBoxAction:(UIButton *)btn {
     BOOL  isRe = [self resignRespondersForTextFields];
    
    if (isRe == NO) {
        if (btn.tag == 1004 ) {
            _signStr = @"Forget";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
            
        }
        if (btn.tag == 1003) {
            _signStr = @"Registered";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
            
        }

    }
}




 //跳转+ 记住密码
- (void)preservationInformation {
    [[NSUserDefaults standardUserDefaults] setObject:_phoneNum.text forKey:@"userCode"];
    [[NSUserDefaults standardUserDefaults] setObject:_password.text forKey:@"passwordText"];
    [LoginViewModel loginWithViewController:self];
}

/** 获取密码的方法*/
- (void)rememberAction {
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isAutomaticLogin"]isEqualToString:@"YES"]) {
        _phoneNum.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCode"];
        _password.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordText"];
        if ([_password.text isEqualToString:@""]) {
            self.loginBtn.userInteractionEnabled = NO;
        }
    }else {
        _phoneNum.text = @"";
        _password.text = @"";
    }
}


/** 确定登陆方法 */
- (IBAction)loginBtnCiake:(UIButton *)sender {
    [_phoneNum resignFirstResponder];
    [_password resignFirstResponder]; //admin 正式密码--in150601
    
    NSString *erorMessage = [self checkUserDetails];
    if (![erorMessage length]) {
        NSMutableString *mutNumStr = [self.phoneNum.text mutableCopy];
        NSMutableString *mutPasStr  = [self.password.text mutableCopy];
       
        NSDictionary *dic = @{@"isPhone":@"true", @"loginName":[NSString stringWithFormat:@"%@",mutNumStr],@"password":[NSString stringWithFormat:@"%@",mutPasStr]};
        
        
        
        [LoginViewModel requestWithUrlForLoginIn:self andParam:dic success:^(LoginModel *model) {
            [self preservationInformation]; // 保存密码
            
            
        } failure:^(NSString *error) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
        }];

    }else {
        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:erorMessage toView:nil];
    }
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"pushRegister"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:_signStr forKey:@"RAVCsignStr"];
    }
}

@end
